package com.ruoyi.project.ledger.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.PermissionService;
import com.ruoyi.project.ledger.domain.LedgerBusinessAccount;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDictDataService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.ledger.domain.LedgerManagementRegistration;
import com.ruoyi.project.ledger.service.ILedgerManagementRegistrationService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jxls.transformer.XLSTransformer;
import org.springframework.web.multipart.MultipartFile;

/**
 * 管理人员登记台账Controller
 *
 * @author ruoyi
 * @date 2020-04-14
 */
@RestController
@RequestMapping("/ledger/management")
public class LedgerManagementRegistrationController extends BaseController
{
    @Autowired
    private ILedgerManagementRegistrationService ledgerManagementRegistrationService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    ServerConfig serverConfig;
    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 查询管理人员登记台账列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:management:list')")
    @GetMapping("/list")
    public TableDataInfo list(LedgerManagementRegistration ledgerManagementRegistration)
    {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerManagementRegistration.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerManagementRegistration.setAreas(areas);
        ledgerManagementRegistration.setManagementCharacters(managementCharacters);
        startPage();
        List<LedgerManagementRegistration> list = ledgerManagementRegistrationService.selectLedgerManagementRegistrationList(ledgerManagementRegistration);
        return getDataTable(list);
    }

    /**
     * 导出管理人员登记台账列表  为啥要多此一举呢  框架李不是有导出的方法嘛
     */
//    @PreAuthorize("@ss.hasPermi('ledger:management:export')")
    @Log(title = "管理人员登记台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LedgerManagementRegistration ledgerManagementRegistration, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerManagementRegistration.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerManagementRegistration.setAreas(areas);
        ledgerManagementRegistration.setManagementCharacters(managementCharacters);
        List<LedgerManagementRegistration> list = ledgerManagementRegistrationService.selectLedgerManagementRegistrationList(ledgerManagementRegistration);
//        if (list != null && list.size() >0){
//            for (LedgerManagementRegistration managementRegistration : list){
//                String post = dictDataService.selectDictLabel("ledger_management_post", managementRegistration.getPost());
//                managementRegistration.setPost(post);
//            }
//        }

//        String tplPath = RuoYiConfig.getProfile() +"/excel/管理人员登记台账.xls";
        String tplPath =this.getClass().getResource("/").getPath() +"excel/管理人员登记台账.xls";
        String fileName = "管理人员登记台账.xls";

//        fileName = FileUtils.setFileDownloadHeader(request, fileName);

        Map<String, List<LedgerManagementRegistration>> beanParams = new HashMap<String, List<LedgerManagementRegistration>>();
        beanParams.put("list", list);

        XLSTransformer former = new XLSTransformer();
        InputStream in = null;
        OutputStream out = null;
        Workbook workbook = null;
        try {
            in = new BufferedInputStream(new FileInputStream(tplPath));
            workbook = former.transformXLS(in, beanParams);
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(fileName));
            workbook.write(out);
           return AjaxResult.success(fileName);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null)
            {
                try
                {
                    workbook.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return AjaxResult.error("导出失败");
    }

    /**
     * 获取管理人员登记台账详细信息
     */
    /*@PreAuthorize("@ss.hasPermi('ledger:management:query')")*/
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(ledgerManagementRegistrationService.selectLedgerManagementRegistrationById(id));
    }

    /**
     * 新增管理人员登记台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:management:add')")
    @Log(title = "管理人员登记台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LedgerManagementRegistration ledgerManagementRegistration)
    {
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long stationId = user.getStationId();
            ledgerManagementRegistration.setStationId(stationId);
            ledgerManagementRegistration.setCreateId(String.valueOf(user.getUserId()));
        } else{
            return AjaxResult.error("当前角色无新增权限");
        }
        if (UserConstants.NOT_UNIQUE.equals(ledgerManagementRegistrationService.checkNameUnique(ledgerManagementRegistration)))
        {
            return AjaxResult.error("新增管理人员失败，身份证已存在");
        }
        return toAjax(ledgerManagementRegistrationService.insertLedgerManagementRegistration(ledgerManagementRegistration));
    }

    /**
     * 修改管理人员登记台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:management:edit')")
    @Log(title = "管理人员登记台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LedgerManagementRegistration ledgerManagementRegistration)
    {
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long stationId = user.getStationId();
            ledgerManagementRegistration.setStationId(stationId);
            ledgerManagementRegistration.setUpdateId(String.valueOf(user.getUserId()));
        }
        else{
            return AjaxResult.error("当前角色无修改权限");
        }
        if (UserConstants.NOT_UNIQUE.equals(ledgerManagementRegistrationService.checkNameUnique2(ledgerManagementRegistration)))
        {
            return AjaxResult.error("修改管理人员失败，身份证已存在");
        }
        return toAjax(ledgerManagementRegistrationService.updateLedgerManagementRegistration(ledgerManagementRegistration));
    }

    /**
     * 删除管理人员登记台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:management:remove')")
    @Log(title = "管理人员登记台账", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(ledgerManagementRegistrationService.deleteLedgerManagementRegistrationByIds(ids));
    }

    @Log(title = "管理人员登记台账", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ledger:management:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        Long stationId = null;
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            stationId = user.getStationId();
        }else{
            return AjaxResult.error("当前角色无导入权限");
        }
        ExcelUtil<LedgerManagementRegistration> util = new ExcelUtil<>(LedgerManagementRegistration.class);
        List<LedgerManagementRegistration> managementRegistrationList = util.importExcel(file.getInputStream());

        String message = ledgerManagementRegistrationService.importManagementRegistration(managementRegistrationList, updateSupport, stationId);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<LedgerManagementRegistration> util = new ExcelUtil<>(LedgerManagementRegistration.class);
        return util.importTemplateExcel("管理人员登记数据模板");
    }
}
